/**
 * 
 */
package cn.gov.msa.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.midi.SysexMessage;

import org.apache.commons.collections.bag.SynchronizedSortedBag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.gov.msa.dao.AuditAnnexMapper;
import cn.gov.msa.dao.FileMapper;
import cn.gov.msa.model.DictionaryDetail;
import cn.gov.msa.service.DictionaryDetailService;
import cn.gov.msa.service.DictionaryService;
import cn.gov.msa.service.FileService;
import cn.gov.msa.util.FileUtil;
import cn.gov.msa.util.InfoObjUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.gov.msa.model.AuditAnnex;


/**
 * @author Administrator
 *
 */

@RestController
public class FileController {
	
	@Autowired
	FileMapper fileMapper;
	@Autowired
	AuditAnnexMapper auditAnnexMapper;
	@Autowired
	FileService fileService;
	
	@Autowired
	DictionaryDetailService dictionaryDetailService;
	
    @RequestMapping(value = "/upload.do")  
    public String upload(String busscode, @RequestParam(value = "file", required = false) MultipartFile[] files, HttpServletRequest request) {  
    	String reslut = "0";
    	String info = InfoObjUtil.Error_upload_NO;
        JSONObject jsonResult = new JSONObject();
        
        
        try {          	
        	
        	if(files.length == 0){
	            reslut = "0";
	            info = "没有上传的文件！";
        	}
        	else{
	            DictionaryDetail dictionaryDetail = dictionaryDetailService.selectDataByDictCodeAndItemCode("DM_WJLB", busscode);
	            
	            
	            if(dictionaryDetail != null){
	            	String dirname = dictionaryDetail.getItemname();
	            	
			        String path = request.getSession().getServletContext().getRealPath("upload/" + dirname);
			        
			        JSONArray jaFile = new JSONArray();
			        
			        for (MultipartFile multipartFile : files) {				
				        String fileName = multipartFile.getOriginalFilename(); 
				        String fileprefixname = fileName.substring(0, fileName.lastIndexOf("."));
				        String filesuffixname = fileName.substring(fileName.lastIndexOf(".") + 1);
				        long filesize = multipartFile.getSize();
				        String filetype = multipartFile.getContentType();	
				        
	
	
				        Date now = new Date( );
				        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddhhmmssSSS");
				        String uploadFileName = ft.format(now) + '.' + filesuffixname;
				        
				        File targetFile = new File(path, uploadFileName);  
				        if(!targetFile.exists()){  
				            targetFile.mkdirs();  
				        }  
				        
				        multipartFile.transferTo(targetFile);    //文件上传		            
			            String fileurl = request.getContextPath()+"/upload/" + dirname + "/" +uploadFileName;
			            
			            //将上传的文件保存到记录表Pub_File      start
			        	cn.gov.msa.model.File file = new cn.gov.msa.model.File();
			        	file.setFilename(fileprefixname);
			        	file.setFilesize(filesize);
			        	file.setFilesuffix(filesuffixname);
			        	file.setFiletype(filetype);
			        	file.setFileurl(fileurl);
			        	
			        	//file.setRelationid(relationid);
			        	
			        	//file.setFileorigin(fileorigin);
			        	
			        	fileMapper.insert(file);
			        	
			        	String fileId = file.getFileid();
			        	
			            //将上传的文件保存到记录表Pub_File end
			        	
			        	JSONObject joFile = new JSONObject();
			        	joFile.put("fileid", fileId);
			        	joFile.put("filename", uploadFileName);
			        	joFile.put("fileurl", fileurl);
			        	jaFile.add(joFile);	
		            }		        
		            JSONObject datas = new JSONObject();	            
		            jsonResult.put("datas", jaFile);
		            reslut = "1";
		            info = InfoObjUtil.Success_upload_OK;
				}
	            else{
		            reslut = "0";
		            info = "没有找到上传目录！";
	            }
        	}
        } catch (Exception e) {  
        	e.printStackTrace();
            reslut = "2";
        	info = InfoObjUtil.Exption_msg;
        }  
        
        jsonResult.put("reslut", reslut);
        jsonResult.put("info", info);
        
        return jsonResult.toString();  
    }   
    

    /**
     * 上传文件
     * @param request
     * @param response
     * @param file 上传的文件，支持多文件
     * @throws Exception
     */
    @RequestMapping("/upload_fileinput.do")
    public String upload_fileinput(HttpServletRequest request,HttpServletResponse response
            ,@RequestParam("file") MultipartFile[] files, String busscode) throws Exception{
    	String reslut = "0";
    	String info = InfoObjUtil.Error_upload_NO;
        JSONObject jsonResult = new JSONObject();
//        String busscode = "01";
        
        try {          	
        	if(files.length == 0){
	            reslut = "0";
	            info = "没有上传的文件！";
        	}
        	else{
	            DictionaryDetail dictionaryDetail = dictionaryDetailService.selectDataByDictCodeAndItemCode("DM_WJLB", busscode);
	            
	            
	            if(dictionaryDetail != null){
	            	String dirname = dictionaryDetail.getItemname();
	            	
			        String path = request.getSession().getServletContext().getRealPath("upload/" + dirname); 
	
			        System.err.println(path);
			        JSONArray jaFile = new JSONArray();
			        
			        for (MultipartFile multipartFile : files) {				
				        String fileName = multipartFile.getOriginalFilename(); 
				        String fileprefixname = fileName.substring(0, fileName.lastIndexOf("."));
				        String filesuffixname = fileName.substring(fileName.lastIndexOf(".") + 1);
				        long filesize = multipartFile.getSize();
				        String filetype = multipartFile.getContentType();	
				        
				       	//如果上传的文件格式不在允许范围，允许上传
				        if(!"'jpg', 'png','gif','txt','sql','xlsx','xls','pdf','pptx','docx','doc','jpeg'".contains(filesuffixname))
				        	return null;

	
				        Date now = new Date( );
				        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddhhmmssSSS");
				        String uploadFileName = ft.format(now) + '.' + filesuffixname;
				        
				        File targetFile = new File(path, uploadFileName);  
				        if(!targetFile.exists()){  
				            targetFile.mkdirs();  
				        }  
				        
				        multipartFile.transferTo(targetFile);    //文件上传		            
			            String fileurl = request.getContextPath()+"/upload/" + dirname + "/" +uploadFileName;
			            
			            //将上传的文件保存到记录表Pub_File      start
			        	cn.gov.msa.model.File file = new cn.gov.msa.model.File();
			        	file.setFilename(fileprefixname);
			        	file.setFilesize(filesize);
			        	file.setFilesuffix(filesuffixname);
			        	file.setFiletype(filetype);
			        	file.setFileurl(fileurl);
			        	
			        	File storecontentFile = new File(targetFile.getPath());
			        	byte[] storecontent = FileUtil.fileTobyte(storecontentFile);
			        	file.setStorecontent(storecontent);
			        	
			        	//file.setRelationid(relationid);
			        	
			        	//file.setFileorigin(fileorigin);
			        	
			        	fileMapper.insert(file);
			        	
			        	String fileId = file.getFileid();
			        	
			            //将上传的文件保存到记录表Pub_File end
			        	
			        	JSONObject joFile = new JSONObject();
			        	joFile.put("fileid", fileId);
			        	joFile.put("filename", fileprefixname + '.' + filesuffixname);
			        	joFile.put("fileurl", fileurl);
			        	jaFile.add(joFile);	
		            }		        
		            JSONObject datas = new JSONObject();	            
		            jsonResult.put("datas", jaFile);
		            reslut = "1";
		            info = InfoObjUtil.Success_upload_OK;
				}
	            else{
		            reslut = "0";
		            info = "没有找到上传目录！";
	            }
        	}
        } catch (Exception e) {  
        	e.printStackTrace();
            reslut = "2";
        	info = InfoObjUtil.Exption_msg;
        }  
        
        jsonResult.put("reslut", reslut);
        jsonResult.put("info", info);
        
        if("1".equals(reslut))
        	return jsonResult.toString();
        else
        	return null;
    }
    
    
    /**
     * 上传文件
     * @param request
     * @param response
     * @param file 上传审核意见附件，支持多文件
     * @throws Exception
     */
    @RequestMapping("/upload_auditannex.do")//目前那前端控件是单个单个文件上传的
    public String upload_auditannex(HttpServletRequest request,HttpServletResponse response
            ,@RequestParam("file") MultipartFile file) throws Exception{
    	String result = "0";
    	String info = InfoObjUtil.Error_upload_NO;
        JSONObject jsonResult = new JSONObject();
//        String busscode = "01";
        
        try {          	
        	if(file==null){
        		result = "0";
	            info = "没有上传的文件！";
        	}
        	else{      			
        		
		        String fileName = file.getOriginalFilename();
		        long filesize = file.getSize();
		        String filetype = file.getContentType();	
		        byte[] storecontent = file.getBytes();
		        AuditAnnex auditAnnex=new AuditAnnex();
		        auditAnnex.setFilename(fileName);
		        auditAnnex.setFilesize(filesize);
		        auditAnnex.setFiletype(filetype);
		        auditAnnex.setStorecontent(storecontent);        	
		        auditAnnexMapper.insert(auditAnnex);
	        	String annexid = auditAnnex.getAnnexid();
	     	    JSONObject joFile = new JSONObject();
	        	joFile.put("annexid", annexid);
	        	joFile.put("filename", fileName);        	        
	            jsonResult.put("datas", joFile);
	            result = "1";
	            info = InfoObjUtil.Success_upload_OK;
        	}
        } catch (Exception e) {  
        	e.printStackTrace();
        	result = "2";
        	info = InfoObjUtil.Exption_msg;
        }  
        
        jsonResult.put("result", result);
        jsonResult.put("info", info);
        
        if("1".equals(result))
        	return jsonResult.toString();
        else
        	return null;
    }
    
    
    
    
    /**
     * 文件下载
     */
	@RequestMapping("/downFiles")
	public void downFiles(HttpServletResponse response, String filename, String fileid) {
		try {

			byte[] b = null;
			response.setHeader("Content-Disposition",
					"attachment; filename=" + new String(filename.getBytes(), "ISO-8859-1"));

			int result = 0;
			JSONObject jsonResult = new JSONObject();

			try {
				cn.gov.msa.model.File file = fileService.selectByPrimaryKey(fileid);
				String content = FileUtil.bytesToHexString(file.getStorecontent());
				jsonResult.put("datas", content);
				result = 1;

			} catch (Exception e) {
				e.printStackTrace();
				result = 2;
			}

			if (1 == result) {
				String content = jsonResult.getString("datas");

				b = FileUtil.hexStringToBytes(content);
				System.out.println("LENGGE");
				OutputStream out = response.getOutputStream();
				out.write(b);
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



